<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>gorm 关联查询</title>
  
    <meta name="author" content="jouyouyun">

    <!-- Le HTML5 shim, for IE6-8 support of HTML elements -->
    <!--[if lt IE 9]>
      <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->

    <!-- Le styles -->
    <link href="/assets/twitter/stylesheets/bootstrap.min.css" type="text/css" rel="stylesheet" media="all">
<link href="/assets/twitter/stylesheets/style.css" type="text/css" rel="stylesheet" media="all">
<link href="/assets/twitter/widgets/google_prettify/stylesheets/twitter-bootstrap.css" type="text/css" rel="stylesheet" media="all">
 

    <!-- Le fav and touch icons -->
  <!-- Update these with your own images
    <link rel="shortcut icon" href="images/favicon.ico">
    <link rel="apple-touch-icon" href="images/apple-touch-icon.png">
    <link rel="apple-touch-icon" sizes="72x72" href="images/apple-touch-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="114x114" href="images/apple-touch-icon-114x114.png">
  -->
  </head>

  <body>

    <div class="navbar">
      <div class="navbar-inner">
        <div class="container">
          <a class="brand" href="/">Jouyouyun&#39;s Blog</a>
          <ul class="nav">
            
              


  <li><a href="/archive">Archive</a></li>


            
              


  <li><a href="/tags">Tags</a></li>


            
              


  <li><a href="/categories">Categories</a></li>


            
              


  <li><a href="/about">About Me</a></li>


            
          </ul>
        </div>
      </div>
    </div>

    <div class="container">

      <div class="content">
        <div class="page-header">
  <h1>gorm 关联查询 </h1>
</div>

<div class="row">
  <div class="span8">
    <p>定义了一个 <code>User</code> 和 <code>Company</code>, <code>User</code> 中可以包含多个 <code>Company</code>, 如下:</p>

<pre><code class="language-go">type User struct {
        ID        int        `gorm:&quot;TYPE:int(11);NOT NULL;PRIMARY_KEY;INDEX&quot;`
        Name      string     `gorm:&quot;TYPE: VARCHAR(255); DEFAULT:'';INDEX&quot;`
        Companies []Company  `gorm:&quot;FOREIGNKEY:UserId;ASSOCIATION_FOREIGNKEY:ID&quot;`
        CreatedAt time.Time  `gorm:&quot;TYPE:DATETIME&quot;`
        UpdatedAt time.Time  `gorm:&quot;TYPE:DATETIME&quot;`
        DeletedAt *time.Time `gorm:&quot;TYPE:DATETIME;DEFAULT:NULL&quot;`
}

type Company struct {
        gorm.Model
        Industry int    `gorm:&quot;TYPE:INT(11);DEFAULT:0&quot;`
        Name     string `gorm:&quot;TYPE:VARCHAR(255);DEFAULT:'';INDEX&quot;`
        Job      string `gorm:&quot;TYPE:VARCHAR(255);DEFAULT:''&quot;`
        UserId   int    `gorm:&quot;TYPE:int(11);NOT NULL;INDEX&quot;`
}
</code></pre>

<p>在查询 <code>User</code> 时希望把 <code>Company</code> 的信息也一并查询, 有以下三种方法:</p>

<h2>Related</h2>

<p>使用 <code>Related</code> 方法, 需要把把 <code>User</code> 查询好, 然后根据 <code>User</code> 定义中指定的 <code>FOREIGNKEY</code> 去查找 <code>Company</code>, 如果没定义, 则调用时需要指定, 如下:</p>

<pre><code class="language-go">var u User
db.First(&amp;u)
db.Model(&amp;u).Related(&amp;u.Companies).Find(&amp;u.Companies)
</code></pre>

<p><code>User</code> 列表时遍历列表一一查询 <code>Company</code></p>

<h2>Association</h2>

<p>使用 <code>Association</code> 方法, 需要把把 <code>User</code> 查询好, 然后根据 <code>User</code> 定义中指定的 <code>AssociationForeignKey</code> 去查找 <code>Company</code>, <strong>必须定义</strong>, 如下:</p>

<pre><code class="language-go">var u User
db.First(&amp;u)
db.Model(&amp;u).Association(&quot;Companies&quot;).Find(&amp;u.Companies)
</code></pre>

<h2>Preload</h2>

<p>使用 <code>Preload</code> 方法, 在查询 <code>User</code> 时先去获取 <code>Company</code> 的记录, 如下:</p>

<pre><code class="language-go">// 查询单条 user
var u User
db.Debug().Preload(&quot;Companies&quot;).First(&amp;u)
// 对应的 sql 语句
// SELECT * FROM users LIMIT 1;
// SELECT * FROM companies WHERE user_id IN (1);

// 查询所有 user
var list []User
db.Debug().Preload(&quot;Companies&quot;).Find(&amp;list)
// 对应的 sql 语句
// SELECT * FROM users;
// SELECT * FROM companies WHERE user_id IN (1,2,3...);
</code></pre>

<hr />

<p>本文中是一对多, 一对一的也是类似的, 完整代码见: <a href="https://github.com/jouyouyun/examples/tree/master/gorm/related">GORM Related</a></p>

    <hr>
    <div class="pagination">
      <ul>
        <ul>
          
          
            <li class="prev disabled"><a>&larr; Previous</a></li>
          

            <li><a href="/archive">Archive</a></li>

          
            <li class="next"><a href="/Blog/python3-%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" title="python3 学习笔记">Next &rarr;</a></li>
          
          
        </ul>
      </ul>
    </div>
    <hr>
    
<div id="disqus_thread"></div>
<script>
    var disqus_developer = 1;
    var disqus_shortname = 'jekyllbootstrap'; // required: replace example with your forum shortname
    /* * * DON'T EDIT BELOW THIS LINE * * */
    (function() {
        var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
    })();
</script>
<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
<a href="http://disqus.com" class="dsq-brlink">blog comments powered by <span class="logo-disqus">Disqus</span></a>

  </div>
  
  <div class="span4">
    <h4>Published</h4>
    <div class="date"><span>2018-12-05</span></div>
    <br>
    <h4>Categories</h4>
    <ul class="tag_box">
    
      <li>
  <a href="/categories/#Blog-ref">Blog <span>23</span></a>
</li>
    
    </ul>
    <br>
    <h4>Tags</h4>
    <ul class="tag_box">
    
      <li>
  <a href="/tags/#gorm-ref">gorm <span>1</span></a>
</li>
    
      <li>
  <a href="/tags/#association-ref">association <span>1</span></a>
</li>
    
    </ul>
  </div>
</div>

      </div>

      <footer>
        <p>&copy; jouyouyun 2013 
          with help from <a href="http://github.com/wendal/gor" target="_blank" title="Gor -- Fast Blog">Gor</a>
          and <a href="http://twitter.github.com/bootstrap/" target="_blank">Twitter Bootstrap</a>
		  and Idea from <a href="http://ruhoh.com" target="_blank" title="The Definitive Technical Blogging Framework">ruhoh</a>
        </p>
      </footer>

    </div> <!-- /container -->

    
<script src="//cdnjscn.b0.upaiyun.com/libs/prettify/r298/prettify.min.js"></script>
<script>
  var pres = document.getElementsByTagName("pre");
  for (var i=0; i < pres.length; ++i) {
    pres[i].className = "prettyprint linenums";
  }
  prettyPrint();
</script>

    
<script type="text/javascript">

  var _gaq = _gaq || [];
  var pluginUrl = '//www.google-analytics.com/plugins/ga/inpage_linkid.js';
  _gaq.push(['_require', 'inpage_linkid', pluginUrl]);
  _gaq.push(['_setAccount', 'UA-123-12']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
  </body>
</html>
